package com.oig.common.filter;

import cn.hutool.core.util.IdUtil;
import com.oig.common.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.lang.NonNull;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class GlobalTraceIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain)
            throws ServletException, IOException {
        String traceId = request.getHeader(CommonConstants.EXPAND_TRACE_ID);   // 从请求头获取 traceId，如果没有就生成。如果是feign调用用传递traceId请求头会有
        //log.debug("get request header traceId:{}", traceId);
        if (StringUtils.isEmpty(traceId)) {
            traceId = IdUtil.objectId();
            //log.debug("create traceId:{}", traceId);
        }
        try {
            MDC.put(CommonConstants.TRACE_ID, traceId);
            // 响应头中添加 traceId 参数，方便排查问题
            response.setHeader(CommonConstants.EXPAND_TRACE_ID, traceId);
            filterChain.doFilter(request, response);
        }  finally {
            MDC.clear();   //要清除
        }
    }

}
